<template>
  <div class="chooseStaffList">
    <a-input v-model:value="staffListData.searchValue" @pressEnter="searchInputEnter" @change="searchInputChange" placeholder="搜索用工单位名称" class="searchInput">
      <template #prefix>
        <img src="./images/searchImg.svg" alt="搜索" />
      </template>
    </a-input>

    <div class="chooseStaff">可选用工单位</div>
    <div class="groupList zdy-scroll">
      <a-tree
        checkable
        :blockNode="true"
        :expanded-keys="staffListData.expandedKeys"
        :auto-expand-parent="staffListData.autoExpandParent"
        :tree-data="staffListData.customerList"
        :checkStrictly="true"
        @expand="onExpand"
        @check="chooseStaff"
        :load-data="onLoadData"
        v-model:checkedKeys="staffListData.checkedStaff"
      >
        <template #title="{ dataRef, title }"> {{ title }} </template>
      </a-tree>
    </div>
  </div>
</template>

<script>
import { reactive, watch } from 'vue'
import $api from '@/server/api'
import { message } from 'ant-design-vue'
import searchInput from '@/components/SearchInput/index.vue'

export default {
  name: 'CustomerList',
  computed: {
    searchInput() {
      return searchInput
    }
  },
  props: {
    checkedStaffList: {
      //已经选中的成员类别
      type: Array,
      default: []
    },
    staffInfoList: {
      //成员列表
      type: Array,
      default: []
    },
    filter: {
      //搜索是否使用过滤方法（用全选功能不要使用，会有问题）
      type: Boolean,
      default: false
    }
  },
  setup(props, context) {
    const staffListData = reactive({
      allStaffChecked: false, //是否选中全部人员
      treeData: [], //成员列表（用于树型展示）
      checkedStaff: [], //当前选中的成员id列表
      staffInfoList: [], //接口获取的成员列表（用于备份）
      allStaffList: [], //所有成员列表（将所有成员放在一个数组内）
      searchValue: '', //搜索参数
      expandedKeys: [], //展开指定树节点
      autoExpandParent: true, //是否自动展开父节点
      loading: false,
      customerList: []
    })

    //获取成员名字（最后两个字）
    const getFirstName = name => {
      return name.substring(name.length - 2)
    }
    //用工单位列表处理
    const shiftCustomerList = list => {
      list.forEach(item => {
        item.key = item.customerId
        item.title = item.customerName
        item.children = []
        item.num = item.count
        // item.disabled = !!item.isPayPlan
        item.isLeaf = !item.count
      })
    }

    //查询用工单位列表
    const customerQuery = () => {
      // const customer = sessionStorage.getItem('customerList')
      // if (customer) {
      //   staffListData.customerList = JSON.parse(customer)
      //   return false
      // }

      staffListData.loading = true
      $api.payPlanApi
        .queryCustomerByaccountNo({})
        .then(res => {
          if (res.code === 1000) {
            staffListData.customerList = res.data
            shiftCustomerList(staffListData.customerList)
            sessionStorage.setItem('customerList', JSON.stringify(staffListData.customerList))
          } else {
            message.error(res.message)
          }
        })
        .catch(err => {
          message.error('用工单位查询失败')
        })
        .finally(() => {
          staffListData.loading = false
        })
    }
    customerQuery()

    //全选/反选成员
    const checkAll = event => {
      const checked = event.target.checked
      //如果当前状态是选中，则是全选；否则是反选
      if (checked) {
        //当前选中的成员列表id
        staffListData.checkedStaff = staffListData.allStaffList.map(item => {
          return item.key
        })

        //当前选中的成员列表详情
        const checkStaffInfoList = staffListData.allStaffList.map(item => {
          return {
            key: item.key,
            title: item.title
          }
        })
        context.emit('checkAllStaff', checkStaffInfoList)
      } else {
        staffListData.checkedStaff = []
        context.emit('checkAllStaff', [])
      }
    }

    //选择成员
    const chooseStaff = (checkedKeys, { node }) => {
      judgeCheckAll() //判断当前人员是否已被全部选中
      const checked = !node.checked //是否选中
      let staffInfo = {
        //当前选中的人员信息
        title: node.title, //成员名称
        key: node.key //成员标识
      }
      context.emit('checkStaff', {
        checked,
        staffInfo
      })
    }

    //判断是否所有人员被选中
    const judgeCheckAll = () => {
      //如果当前选中的人员列表人数，大于等于所有成员人员数，则代表全部人员被选中；否则则未全部被选中
      if (staffListData.checkedStaff.checked) {
        staffListData.allStaffChecked = staffListData.checkedStaff.checked.length >= staffListData.allStaffList.length
      } else {
        staffListData.allStaffChecked = staffListData.checkedStaff.length >= staffListData.allStaffList.length
      }
    }

    //将成员列表进行数据处理
    const handleStaffList = list => {
      list.forEach(item => {
        if (!item.isGroup) {
          //如果当前项不是团队，则是成员，将成员的accontNo赋值给key
          item.key = item.accountNo
        } else if (item.children && item.children.length > 0) {
          //如果当前项的children存在成员，则进行对children内容遍历
          handleStaffList(item.children)
        }
      })
      return list
    }

    //将所有成员拆到一个数组内
    const getAllStaff = list => {
      list.forEach(item => {
        if (!item.isGroup) {
          //如果当前项不是团队，则是成员，将该成员添加到所有成员列表的数组里面
          staffListData.allStaffList.push(item)
        } else if (item.children && item.children.length > 0) {
          //如果当前项的children存在成员，则进行对children内容遍历
          const copyItem = JSON.parse(JSON.stringify(item))
          getAllStaff(item.children)

          copyItem.children = [] //去除子组件
          staffListData.allStaffList.push(copyItem)
        }
      })
    }

    //监听获取到的成员列表
    watch(
      () => props.staffInfoList,
      () => {
        // let staffInfoList = handleStaffList(props.staffInfoList);
        try {
          let staffInfoList = props.staffInfoList
          staffListData.staffInfoList = JSON.parse(JSON.stringify(staffInfoList))
          staffListData.treeData = JSON.parse(JSON.stringify(staffInfoList))
          const staffList = JSON.parse(JSON.stringify(staffInfoList))
          staffListData.allStaffList = []
          getAllStaff(staffList)
        } catch (e) {
          console.log(e)
        }
      },
      {
        immediate: true
      }
    )

    //监听已经选中的成员列表
    watch(
      () => props.checkedStaffList,
      list => {
        staffListData.checkedStaff = list.map(item => {
          return item.key
        })
        judgeCheckAll() //判断所有成员是否被选中
      },
      {
        immediate: true
      }
    )

    //获取父级key
    const getParentKey = (key, tree) => {
      let parentKey
      tree.forEach(node => {
        if (node.children) {
          if (node.children.some(item => item.key === key)) {
            parentKey = node.key
          } else if (getParentKey(key, node.children)) {
            parentKey = getParentKey(key, node.children)
          }
        }
      })
      return parentKey
    }

    /*展开/收起节点时触发*/
    const onExpand = keys => {
      staffListData.expandedKeys = keys
      staffListData.autoExpandParent = false
    }

    const onLoadData = treeNode => {
      return new Promise(resolve => {
        $api.payPlanApi.queryTwoCustomer({ customerId: treeNode.dataRef.key }).then(res => {
          if (res.code === 1000) {
            treeNode.dataRef.children = res.data.map(item => {
              return {
                title: item.customerName,
                key: item.customerId,
                isLeaf: false,
                count: item.count
              }
            })

            console.log(staffListData.treeData, 'staffListData.treeData')
            // staffListData.treeData = [...staffListData.treeData]
          }
        })
        resolve()
      })
    }

    // 根据输入框的值进行模糊查询
    const searchInputEnter = () => {
      if (!staffListData.searchValue) return false
      staffListData.customerList = filterData(staffListData.customerList, staffListData.searchValue)
    }

    // 封装过滤函数，传递一个 中文字符串 模糊查询相关数据
    const filterData = (data, value) => {
      return data.filter(item => {
        if (item.title.includes(value)) {
          return true
        } else if (item.children) {
          item.children = filterData(item.children, value)
          return item.children.length
        }
      })
    }

    const searchInputChange = () => {
      if (!staffListData.searchValue) {
        customerQuery()
      }
    }

    return {
      staffListData,
      getFirstName,
      chooseStaff,
      checkAll,
      onExpand,
      onLoadData,
      searchInputEnter,
      searchInputChange
    }
  }
}
</script>

<style lang="less" scoped>
.chooseStaffList {
  height: 100%;
  // padding: 0px 24px 0px 32px;
  overflow-y: auto;
  overflow-x: hidden;
  .searchInput {
    width: calc(100% - 24px - 32px);
    margin: 0px 24px 24px 32px;
  }
  .chooseStaff {
    width: calc(100% - 24px - 32px);
    margin: 0px 24px 24px 32px;
    line-height: 22px;
    font-size: 16px;
    font-weight: bold;
    &:after {
      display: block;
      height: 0px;
      clear: both;
      content: '';
      visibility: hidden;
    }
    .checkAllStaff {
      float: right;
    }
  }
  .groupList {
    padding: 0 16px 0 32px;
    height: calc(100% - 32px - 24px - 22px - 40px);
    overflow-y: auto;
    overflow-x: hidden;
    .teamImg {
      display: inline-block;
      width: 24px;
      height: 24px;
      line-height: 24px;
      background: #5975fb;
      color: #ffffff;
      border-radius: 50%;
      text-align: center;
      font-size: 13px;
      margin-right: 8px;
      i {
        display: block;
        font-style: normal;
        transform: scale(0.6);
      }
    }
  }
}
.tips {
  font-size: 12px;
  color: rgba(0, 0, 0, 0.45);
  margin-left: 8px;
}
</style>

<style lang="less">
.chooseStaffList {
  .groupList {
    user-select: none;
    .ant-tree .ant-tree-treenode {
      position: relative;
      padding: 0px 30px 0px 0px;
      margin-bottom: 8px;
    }
    .ant-tree-checkbox {
      position: absolute;
      right: 0px;
      top: 8px;
      .ant-tree-checkbox-inner {
        border-radius: 2px;
      }
    }
    .ant-tree-switcher {
      line-height: 40px;
      .ant-tree-switcher-icon {
        font-size: 14px;
        color: #b7b9bf;
      }
    }
    .ant-tree .ant-tree-node-content-wrapper {
      height: 40px;
      line-height: 40px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .ant-tree-indent,
    .ant-tree-switcher.ant-tree-switcher-noop {
      background: #ffffff;
    }
    .ant-tree-switcher.ant-tree-switcher-noop {
      display: none;
    }
    .ant-tree-treenode:hover {
      background: #f8f8f9;
      .ant-tree-node-content-wrapper {
        background: none;
      }
    }
    .ant-tree-treenode-selected {
      background: #f8f8f9;
      .ant-tree-node-content-wrapper.ant-tree-node-selected {
        background: none;
      }
    }
  }
}
</style>
